package main.base;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

import main.exception.CheckResourceNotValidException;
import main.validator.CheckItem;
import main.validator.CheckResouceParser;
import main.validator.DataChecker;
import main.validator.Validator;

import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.dom4j.DocumentException;
import org.xml.sax.SAXException;

/**
 * TPL 基础类。其他自定自定义tpl实现应该继承改类
 */
public class BaseResourceImpl implements Resource {
	private CheckResouceParser checkParser;

	static {
		//SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
	}


	public BaseResourceImpl() {
		this.checkParser = new CheckResouceParser();
	}

	protected String getRawString(String fileName) throws IOException {
		String currDir = DataChecker.class.getClassLoader().getResource("").getPath();
		File file = new File(currDir + "/" + fileName);
		InputStream ins = new FileInputStream(file);
		InputStreamReader insr = new InputStreamReader(ins, "gbk");
		BufferedReader br = new BufferedReader(insr);
		StringBuffer sb = new StringBuffer();
		String aLine = null;
		while (null != (aLine = br.readLine())) {
			sb.append(aLine.trim());
			sb.append("\n");
		}
		ins.close();
		insr.close();
		br.close();
		return sb.toString().trim();
	}

	protected String renderFromStr(String str,Map<Object,Object> userData){
		try{
			return VelocityRender.render(str, userData);
		}catch(URISyntaxException e){
			e.printStackTrace();
		} catch (ParseErrorException e) {
			e.printStackTrace();
		} catch (MethodInvocationException e) {
			e.printStackTrace();
		} catch (ResourceNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public List<CheckItem> getCheckResource(Map<Object, Object> userData) {

		List<CheckItem> tplItems = null;

		try {
			String checkStr = this.getRawString("check.xml");
			String xml = this.renderFromStr(checkStr,userData);
			tplItems = this.checkParser.parseCheckResource(xml);
		} catch (DocumentException e) {
			e.printStackTrace();
			System.out.println("check.xml解析错误");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("check.xml 读取错误");
		} catch (CheckResourceNotValidException e) {
			e.printStackTrace();
			System.out.println("check.xml 无效，可能是由于语法错误");
		} catch (SAXException e) {
			e.printStackTrace();
			System.out.println("check.xml 语法错误");
		}

		return tplItems;
	}

	@Override
	public Map<String, Validator> getCustomValidators() {
		// TODO Auto-generated method stub
		return null;
	}
}